# -*- coding:utf-8 -*-
from django import http
from django.contrib import messages, auth
from django.shortcuts import redirect, render_to_response
from django.core.urlresolvers import reverse
from django.template.context import RequestContext
from django.core.urlresolvers import reverse

#from .forms import CompleteReg

from loginza import signals, models
from loginza.templatetags.loginza_widget import _return_path
import simplejson as json

def log(s):
    f = open('/tmp/loginza.txt', 'a')
    try: 
        s = str(s.encode('utf-8'))
        f.write(s+"\n")
    except: pass
    f.close()

def loginza_error_handler(sender, error, **kwargs):
    messages.error(sender, error.message)

signals.error.connect(loginza_error_handler)

def loginza_auth_handler(sender, user, identity, **kwargs):
    try:
        # it's enough to have single identity verified to treat user as verified
        user_map = models.UserMap.objects.get(user=user, verified=True)
        #update_loginza_userinfo(user_map)
        auth.login(sender, user)
    except models.UserMap.DoesNotExist:
        sender.session['users_complete_reg_id'] = identity.id
        return redirect(reverse('users_complete_registration'))

signals.authenticated.connect(loginza_auth_handler)

def loginza_login_required(sender, **kwargs):
    messages.warning(sender, u'Функция доступна только авторизованным пользователям.')

signals.login_required.connect(loginza_login_required)


def complete_registration(request):
    if request.user.is_authenticated():
        return http.HttpResponseForbidden(u'Вы попали сюда по ошибке')
    try:
        identity_id = request.session.get('users_complete_reg_id', None)
        user_map = models.UserMap.objects.get(identity__id=identity_id)
        
    except models.UserMap.DoesNotExist:
        return http.HttpResponseForbidden(u'Вы попали сюда по ошибке')

    user_map.user.username = user_map.user.username
    #log( dir(user_map.user) )
    user_map.user.email = user_map.user.email
    user_map.user.save()

    user_map.verified = True
    user_map.save()

    user = auth.authenticate(user_map=user_map)
    auth.login(request, user)

    messages.info(request, u'Добро пожаловать!')

    del request.session['users_complete_reg_id']

    return redirect(reverse('home'))

def _old_update_loginza_userinfo(user_map = None, **kwargs):
    from authfuncs import get_user_profile
    log('update_loginza_userinfo')
    if user_map == None:
        try:
            if kwargs('user', None):
                user_map = models.UserMap.objects.get(user = kwargs['user'])
            elif kwargs('request', None):
                user_map = models.UserMap.objects.get(user = kwargs['request'].user)
            elif kwargs('profile', None):
                user_map = models.UserMap.objects.get(user = kwargs['profile'].user)
        except: pass

    if not user_map: return False

    soc_info = json.loads(user_map.identity.data)
    name_info = soc_info.get('name', False)
    if name_info:
        first_name = name_info.get('first_name', None)
        last_name = name_info.get('last_name', None)
        full_name = name_info.get('full_name', None)

    nickname = soc_info.get('nickname', None)
    photo = soc_info.get('photo', None)
    email = soc_info.get('email', None)

    profile = get_user_profile(user = user_map.user)
    #request.session['user_profile'] = None

    profile_changed = False
    user_changed = False

    if nickname: profile.nickname = nickname
    if first_name:
        profile.user.first_name = first_name
        log('profile.user.first_name '+profile.user.first_name)
        if last_name: 
            profile.user.last_name = last_name
            log('profile.user.last_name '+profile.user.last_name)
        user_changed = True
    else:
        if full_name: 
            profile.user.first_name = full_name
            log('profile.user.first_name full_name'+profile.user.first_name)
            user_changed = True
    if photo:
        profile.photo = photo
        log('photo '+profile.photo)
        profile_changed = True
    if nickname:
        profile.nickname = nickname
        log('profile.nickname'+profile.nickname)
        profile_changed = True
    
    if user_changed: profile.user.save()
    if profile_changed: profile.save()
    
    return profile


